<template>
  <el-dialog
    title="收货明细"
    top="5vh"
    :visible.sync="dialogVisible"
    width="90%"
    :close-on-click-modal="false"
    append-to-body
  >
    <div class="receipt-details">
      <!-- 采购单信息 -->
      <div class="menu-info">
        <el-descriptions :column="3" border>
          <el-descriptions-item label="菜单标题">{{ currentMenu?.title }}</el-descriptions-item>
          <el-descriptions-item label="菜单日期">{{ formatDate(currentMenu?.menu_date) }}</el-descriptions-item>
          <el-descriptions-item label="供应商">{{ currentMenu?.supplier?.name }}</el-descriptions-item>
          <el-descriptions-item label="采购员">{{ currentMenu?.purchaser?.name }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag type="success">已收货</el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 菜品明细表格 -->
      <div class="dish-details">
        <div class="table-header">
          <h4>菜品明细</h4>
          <el-button 
            type="primary" 
            size="small" 
            icon="el-icon-download"
            @click="exportToExcel"
            :loading="exporting"
            :disabled="menuItems.length === 0"
          >
            导出Excel
          </el-button>
        </div>
        <el-alert
          title="表格说明"
          type="info"
          :closable="false"
          show-icon
          style="margin-bottom: 15px;"
        >
        </el-alert>

        <div slot="description">
            <p>• 官方参考价格合计 = 官方参考价格 × 实际收货数量</p>
            <p>• 供应商报价合计 = 供应商报价 × 实际收货数量</p>
            <p>• 实际采购价格合计 = 实际采购价格 × 实际收货数量</p>
          </div>
        <el-table
          :data="menuItems"
          v-loading="loading"
          border
          stripe
          :show-summary="true"
          :summary-method="getSummaries"
        >
          <el-table-column prop="dish.category" label="菜品分类" width="100">
            <template slot-scope="scope">
              {{ scope.row.dish?.category || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="dish.name" label="菜品名称" width="150">
            <template slot-scope="scope">
              {{ scope.row.dish?.name || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="dish.unit" label="单位" width="80">
            <template slot-scope="scope">
              {{ scope.row.dish?.unit || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="base_price" label="官方参考价格" width="100">
            <template slot-scope="scope">
              ¥{{ scope.row.base_price }}
            </template>
          </el-table-column>
          <el-table-column prop="supplier_quoted_price" label="供应商报价" width="120">
            <template slot-scope="scope">
              ¥{{ scope.row.supplier_quoted_price }}
            </template>
          </el-table-column>
          <el-table-column prop="planned_quantity" label="计划采购数量" width="120">
            <template slot-scope="scope">
              {{ scope.row.planned_quantity }}
            </template>
          </el-table-column>
          <el-table-column prop="actual_price" label="供应商-实际采购价" width="140">
            <template slot-scope="scope">
              ¥{{ scope.row.actual_price || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="actual_quantity" label="供应商-实际采购数量" width="140">
            <template slot-scope="scope">
              {{ scope.row.actual_quantity || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="actual_quantity2" label="实际收货数量" width="120">
            <template slot-scope="scope">
              {{ scope.row.actual_quantity2 || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="quality_rating" label="品质评价" width="100">
            <template slot-scope="scope">
              <el-tag
                :type="getQualityTagType(scope.row.quality_rating)"
                size="mini"
              >
                {{ scope.row.quality_rating || '-' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" min-width="150">
            <template slot-scope="scope">
              {{ scope.row.remark || '-' }}
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 收货统计 -->
      <div class="receipt-summary" v-if="menuItems.length > 0">
        <el-alert
          title="收货统计"
          type="success"
          :closable="false"
          show-icon
        >
        </el-alert>

        <div slot="description">
          <p>总菜品数：{{ menuItems.length }} 个 | 已收货菜品：{{ receivedCount }} 个</p>
          <p>总计划数量：{{ totalPlannedQuantity }} | 总实际收货数量：{{ totalActualQuantity }}</p>
        </div>
      </div>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">关闭</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { http } from '@/api'

export default {
  name: 'ReceiptDetails',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    currentMenu: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      dialogVisible: false,
      loading: false,
      menuItems: [],
      exporting: false // 新增导出按钮加载状态
    }
  },
  computed: {
    receivedCount() {
      return this.menuItems.filter(item =>
        item.actual_quantity2 && item.actual_quantity2 > 0
      ).length;
    },
    averageQuality() {
      const qualityMap = {
        '优秀': 5,
        '良好': 4,
        '一般': 3,
        '较差': 2,
        '不合格': 1
      };

      const ratedItems = this.menuItems.filter(item =>
        item.quality_rating && qualityMap[item.quality_rating]
      );

      if (ratedItems.length === 0) return '暂无评价';

      const totalScore = ratedItems.reduce((sum, item) =>
        sum + qualityMap[item.quality_rating], 0
      );

      const average = totalScore / ratedItems.length;

      if (average >= 4.5) return '优秀';
      if (average >= 3.5) return '良好';
      if (average >= 2.5) return '一般';
      if (average >= 1.5) return '较差';
      return '不合格';
    },
    totalPlannedQuantity() {
      return this.menuItems.reduce((sum, item) =>
        sum + (item.planned_quantity || 0), 0
      ).toFixed(2);
    },
    totalActualQuantity() {
      return this.menuItems.reduce((sum, item) =>
        sum + (item.actual_quantity2 || 0), 0
      ).toFixed(2);
    },
    // 价格统计
    totalBasePrice() {
      return this.menuItems.reduce((sum, item) =>
        sum + (parseFloat(item.base_price) || 0), 0
      ).toFixed(2);
    },
    totalSupplierQuotedPrice() {
      return this.menuItems.reduce((sum, item) =>
        sum + (parseFloat(item.supplier_quoted_price) || 0), 0
      ).toFixed(2);
    },
    totalActualPrice() {
      return this.menuItems.reduce((sum, item) =>
        sum + (parseFloat(item.actual_price) || 0), 0
      ).toFixed(2);
    },
    // 金额统计（价格 × 数量）
    totalBaseAmount() {
      return this.menuItems.reduce((sum, item) =>
        sum + ((parseFloat(item.base_price) || 0) * (parseFloat(item.actual_quantity2) || 0)), 0
      ).toFixed(2);
    },
    totalSupplierQuotedAmount() {
      return this.menuItems.reduce((sum, item) =>
        sum + ((parseFloat(item.supplier_quoted_price) || 0) * (parseFloat(item.actual_quantity2) || 0)), 0
      ).toFixed(2);
    },
    totalActualAmount() {
      return this.menuItems.reduce((sum, item) =>
        sum + ((parseFloat(item.actual_price) || 0) * (parseFloat(item.actual_quantity2) || 0)), 0
      ).toFixed(2);
    }
  },
  watch: {
    visible(val) {
      this.dialogVisible = val
      if (val && this.currentMenu) {
        this.loadMenuItems()
      }
    },
    dialogVisible(val) {
      this.$emit('update:visible', val)
      if (!val) {
        this.resetData()
      }
    }
  },
  methods: {
    formatDate(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      return date.toLocaleDateString('zh-CN');
    },

    getQualityTagType(quality) {
      const typeMap = {
        '优秀': 'success',
        '良好': 'primary',
        '一般': 'warning',
        '较差': 'danger',
        '不合格': 'info'
      };
      return typeMap[quality] || 'info';
    },

    async loadMenuItems() {
      this.loading = true
      try {
        const res = await http.dailyMenuItem.getMenuItems(this.currentMenu.id);

        this.menuItems = res.data || [];

      } catch (error) {
        console.error('加载菜品明细失败:', error);
        this.$message.error('加载菜品明细失败');
      } finally {
        this.loading = false;
      }
    },

    resetData() {
      this.menuItems = [];
    },

    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        
        // 根据列类型进行不同的汇总计算
        if (column.property === 'base_price') {
          // 官方参考价格总金额 = 官方参考价格 × 实际收货数量
          const sum = data.reduce((prev, curr) => {
            const price = parseFloat(curr.base_price) || 0;
            const quantity = parseFloat(curr.actual_quantity2) || 0;
            return prev + (price * quantity);
          }, 0);
          sums[index] = `¥${sum.toFixed(2)}`;
        } else if (column.property === 'supplier_quoted_price') {
          // 供应商报价总金额 = 供应商报价 × 实际收货数量
          const sum = data.reduce((prev, curr) => {
            const price = parseFloat(curr.supplier_quoted_price) || 0;
            const quantity = parseFloat(curr.actual_quantity2) || 0;
            return prev + (price * quantity);
          }, 0);
          sums[index] = `¥${sum.toFixed(2)}`;
        } else if (column.property === 'actual_price') {
          // 实际采购价格总金额 = 实际采购价格 × 实际收货数量
          const sum = data.reduce((prev, curr) => {
            const price = parseFloat(curr.actual_price) || 0;
            const quantity = parseFloat(curr.actual_quantity2) || 0;
            return prev + (price * quantity);
          }, 0);
          sums[index] = `¥${sum.toFixed(2)}`;
        } else if (column.property === 'planned_quantity' || 
                   column.property === 'actual_quantity' || 
                   column.property === 'actual_quantity2') {
          // 数量列直接求和
          const values = data.map(item => {
            const value = item[column.property];
            return isNaN(value) ? 0 : parseFloat(value);
          });
          
          if (!values.every(value => isNaN(value))) {
            const sum = values.reduce((prev, curr) => {
              return prev + curr;
            }, 0);
            sums[index] = sum.toFixed(2);
          } else {
            sums[index] = '';
          }
        } else {
          sums[index] = '';
        }
      });
      
      return sums;
    },

    // 导出Excel功能
    async exportToExcel() {
      this.exporting = true;
      try {
        // 导入Excel相关库
        const XLSX = require('xlsx');
        const FileSaver = require('file-saver');
        
        // 准备导出数据
        const exportData = this.prepareExportData();
        
        // 创建工作簿
        const wb = XLSX.utils.book_new();
        
        // 创建工作表
        const ws = XLSX.utils.json_to_sheet(exportData);
        
        // 设置列宽
        const colWidths = [
          { wch: 15 }, // 菜品分类
          { wch: 20 }, // 菜品名称
          { wch: 10 }, // 单位
          { wch: 15 }, // 官方参考价格
          { wch: 15 }, // 供应商报价
          { wch: 15 }, // 计划采购数量
          { wch: 15 }, // 实际采购价格
          { wch: 15 }, // 实际采购数量
          { wch: 15 }, // 实际收货数量
          { wch: 15 }, // 品质评价
          { wch: 30 }, // 备注
          { wch: 20 }, // 官方参考价格总金额
          { wch: 20 }, // 供应商报价总金额
          { wch: 20 }  // 实际采购价格总金额
        ];
        ws['!cols'] = colWidths;
        
        // 设置表头样式（第一行加粗）
        const range = XLSX.utils.decode_range(ws['!ref']);
        for (let col = range.s.c; col <= range.e.c; col++) {
          const cellAddress = XLSX.utils.encode_cell({ r: 0, c: col });
          if (ws[cellAddress]) {
            ws[cellAddress].s = { font: { bold: true } };
          }
        }
        
        // 设置合计行样式（最后一行加粗）
        const lastRow = range.e.r;
        for (let col = range.s.c; col <= range.e.c; col++) {
          const cellAddress = XLSX.utils.encode_cell({ r: lastRow, c: col });
          if (ws[cellAddress]) {
            ws[cellAddress].s = { font: { bold: true } };
          }
        }
        
        // 添加工作表到工作簿
        XLSX.utils.book_append_sheet(wb, ws, '收货明细');
        
        // 生成文件名
        const fileName = `${this.currentMenu?.title || '收货明细'}-${this.formatDate(this.currentMenu?.menu_date)}.xlsx`;
        
        // 导出文件
        const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
        const blob = new Blob([wbout], { type: 'application/octet-stream' });
        FileSaver.saveAs(blob, fileName);
        
        this.$message.success('导出成功！');
      } catch (error) {
        console.error('导出失败:', error);
        this.$message.error('导出失败');
      } finally {
        this.exporting = false;
      }
    },
    
    // 准备导出数据
    prepareExportData() {
      const data = [];
      
      // 添加数据行（不添加重复的表头）
      this.menuItems.forEach(item => {
        data.push({
          '菜品分类': item.dish?.category || '-',
          '菜品名称': item.dish?.name || '-',
          '单位': item.dish?.unit || '-',
          '官方参考价格': `¥${item.base_price}`,
          '供应商报价': `¥${item.supplier_quoted_price}`,
          '计划采购数量': item.planned_quantity,
          '实际采购价格': item.actual_price ? `¥${item.actual_price}` : '-',
          '实际采购数量': item.actual_quantity || '-',
          '实际收货数量': item.actual_quantity2 || '-',
          '品质评价': item.quality_rating || '-',
          '备注': item.remark || '-',
          '官方参考价格总金额': `¥${((parseFloat(item.base_price) || 0) * (parseFloat(item.actual_quantity2) || 0)).toFixed(2)}`,
          '供应商报价总金额': `¥${((parseFloat(item.supplier_quoted_price) || 0) * (parseFloat(item.actual_quantity2) || 0)).toFixed(2)}`,
          '实际采购价格总金额': `¥${((parseFloat(item.actual_price) || 0) * (parseFloat(item.actual_quantity2) || 0)).toFixed(2)}`
        });
      });
      
      // 添加汇总行
      data.push({
        '菜品分类': '合计',
        '菜品名称': '',
        '单位': '',
        '官方参考价格': '',
        '供应商报价': '',
        '计划采购数量': this.totalPlannedQuantity,
        '实际采购价格': '',
        '实际采购数量': '',
        '实际收货数量': this.totalActualQuantity,
        '品质评价': '',
        '备注': '',
        '官方参考价格总金额': `¥${this.getTotalBaseAmount()}`,
        '供应商报价总金额': `¥${this.getTotalSupplierQuotedAmount()}`,
        '实际采购价格总金额': `¥${this.getTotalActualAmount()}`
      });
      
      return data;
    },
    
    // 获取汇总金额的辅助方法
    getTotalBaseAmount() {
      return this.menuItems.reduce((sum, item) => {
        const price = parseFloat(item.base_price) || 0;
        const quantity = parseFloat(item.actual_quantity2) || 0;
        return sum + (price * quantity);
      }, 0).toFixed(2);
    },
    
    getTotalSupplierQuotedAmount() {
      return this.menuItems.reduce((sum, item) => {
        const price = parseFloat(item.supplier_quoted_price) || 0;
        const quantity = parseFloat(item.actual_quantity2) || 0;
        return sum + (price * quantity);
      }, 0).toFixed(2);
    },
    
    getTotalActualAmount() {
      return this.menuItems.reduce((sum, item) => {
        const price = parseFloat(item.actual_price) || 0;
        const quantity = parseFloat(item.actual_quantity2) || 0;
        return sum + (price * quantity);
      }, 0).toFixed(2);
    }
  }
}
</script>

<style scoped lang="scss">
.receipt-details {
  .menu-info {
    margin-bottom: 20px;
  }

  .dish-details {
    margin-bottom: 20px;

    .table-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;

      h4 {
        margin: 0;
        color: #303133;
        font-size: 16px;
        font-weight: bold;
      }
    }

    h4 {
      margin: 0 0 15px 0;
      color: #303133;
      font-size: 16px;
    }

    // 汇总行样式
    ::v-deep .el-table__footer-wrapper {
      .el-table__footer {
        background-color: #f5f7fa;
        
        td {
          background-color: #f5f7fa;
          color: #409EFF;
          font-weight: bold;
          font-size: 14px;
        }
      }
    }
  }

  .receipt-summary {
    margin-top: 20px;

    .stat-section {
      h5 {
        margin: 0 0 10px 0;
        color: #409EFF;
        font-size: 14px;
        font-weight: bold;
      }

      p {
        margin: 5px 0;
        color: #606266;
        font-size: 13px;
        line-height: 1.5;
      }
    }
  }
}

.dialog-footer {
  text-align: right;
}
</style>
